#! /usr/bin/python
# -*- coding: cp1250 -*-
#sys.path.append(r'C:\x\y')

import re, string, sys, glob
import decimal
import pepe.datetimex.shift as pds

D = decimal.Decimal

date_shift = lambda fxdate_s, shift_n: \
             pds.byDate(fxdate_s, shift_n)
dcm = lambda x_s: re.sub(',','', x_s)
zf4 = lambda x_s: string.zfill(x_s, 4)

rates_h = {}
dir_s = 'cnb-rates-data/'
rates_h['2006'] = open(dir_s+'CNB_Kurzy_rok2006.txt','r').readlines()
rates_h['2007'] = open(dir_s+'CNB_Kurzy_rok2007.txt','r').readlines()

ERROR_CODES = [ 'ERROR: requested fxdate not found: ',
                'ERROR: unsuported fxcode: ']

def get( fxcode = 'EUR', fxdate = '2007-01-02'):
    out_l = [[fxcode,fxdate]]
    FX_INDEX = FX_RATE = lncnt_n = 0

    for line_s in rates_h[fxdate[:4]]:
        cols_l = string.split(line_s, '|')
        if lncnt_n == 0:
            for i,v in enumerate(cols_l):
                if v[-3:] == fxcode:
                    FX_INDEX = i
                    FX_AMOUNT = string.split(cols_l[FX_INDEX],' ')[0]
        if lncnt_n != 0 and FX_INDEX == 0:
            out_l.extend([['', ''],[ERROR_CODES[1],0]])
            return out_l
        elif lncnt_n != 0 and FX_INDEX != 0:
            dd,mm,yyyy = string.split(cols_l[0][:],'.')
            fileFxDate = yyyy+'-'+mm+'-'+dd
            if fxdate == fileFxDate:
                FX_RATE = D(re.sub(',', '.',cols_l[FX_INDEX]))
                out_l.extend([[FX_RATE, FX_AMOUNT],['OK',1]])
                return out_l
        lncnt_n += 1

    day_back = date_shift(fxdate, -1)
    if get( fxcode, fxdate = day_back)[2][1] <> 1:
        day_back = date_shift(fxdate, -1)
    else:
        return get( fxcode, fxdate = day_back)

def main():
    print get( fxcode = 'EUR',fxdate = '2006-01-03')
    print get( fxcode = 'SKK',fxdate = '2007-01-01')

if __name__ == "__main__":
    main()
